package cn.wx.shop.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wx.shop.entity.Category;
import cn.wx.shop.entity.Goods;
import cn.wx.shop.entity.page.Page;
import cn.wx.shop.result.AjaxResult;
import cn.wx.shop.service.CategoryService;
import cn.wx.shop.service.GoodsService;

@Controller
@RequestMapping("/sys/goods")
public class GoodsController {

	@Autowired
	GoodsService goodsService;

	@Autowired
	CategoryService categoryService;

	@RequestMapping("/list")
	public String list(@RequestParam(required = false, defaultValue = "1") Integer pageNo, Model model) {
		
		Page<Goods> pageInfo = goodsService.selectByPage(pageNo);
		model.addAttribute("pageInfo", pageInfo);
		return "goods";
	}

	@ResponseBody
	@RequestMapping("/listByCid")
	public List<Goods> getGoodsByCid(Integer cid){
		List<Goods> goods = goodsService.getGoodsByCid(cid);
		return goods;
	}

	@RequestMapping("/toAdd")
	public String toAdd(Model model) {
		// 一级分类数据
		List<Category> categoryList = categoryService.categoryByParentId(0);
		model.addAttribute("categoryList", categoryList);
		return "goods_add";
	}

	@ResponseBody
	@RequestMapping("/add")
	public AjaxResult add(Goods goods) {
		int n = goodsService.addGoods(goods);
		if (n > 0) {
			return AjaxResult.succes("添加商品成功");
		}
		return AjaxResult.error("添加商品失败");
	}
	
	@RequestMapping("/get/{id}")
	public String get(@PathVariable Integer id,Model model){

		//商品详情
		Goods good = goodsService.selectById(id);
		//商品分类详情
		Category category = categoryService.selectById(good.getCategoryId());
		List<Category> category1List = categoryService.categoryByParentId(0);
		List<Category> category2List = categoryService.categoryByParentId(category.getParentId());
		
		model.addAttribute("good", good);
		model.addAttribute("category", category);
		model.addAttribute("category1List", category1List);
		model.addAttribute("category2List", category2List);
		return "goods_update";
	}
	
	@ResponseBody
	@RequestMapping("/update")
	public AjaxResult update(Goods goods) {
		int n = goodsService.updateGoods(goods);
		if (n > 0) {
			return AjaxResult.succes("更新商品成功");
		}
		return AjaxResult.error("更新商品失败");
	}

	@ResponseBody
	@RequestMapping("/detail/{id}")
	public Goods detail(@PathVariable Integer id){
		return goodsService.selectById(id);
	}
}
